//
//  CHSuperMenu.m
//  CarFile
//
//  Created by 陈浩 on 2018/1/22.
//  Copyright © 2018年 陈浩. All rights reserved.
//

#import "CHSuperMenu.h"
#import "CHDatePickerView.h"
#import "PJ_Model.h"
@interface CHSuperMenu ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource>
{

NSString *_dateStr;

NSInteger _dayRange;
NSInteger _dayRange1;

NSMutableArray *_MArray;

NSInteger _year;
NSInteger _month;
NSInteger _day;



}

@property (nonatomic ,strong) NSArray *titles;
@property (nonatomic ,strong) UIButton *selectedBtn;
@property (nonatomic ,assign) BOOL isShow;
//@property (nonatomic ,strong) NSMutableArray *dateArr;
@property (nonatomic, assign) NSInteger numberOfColumn;  //列数
@property (nonatomic ,assign) NSInteger currentSelectedColumn;   //  当前选中列
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UIButton *coverBtn;      //  遮罩层
@property (nonatomic ,strong) UIPickerView *pickerView;
@property (nonatomic ,assign) NSInteger selectRow;
@property (nonatomic ,assign) NSInteger selectComponent;
@property (nonatomic ,strong) UIView *datePickerView;
@property (nonatomic ,copy)  NSString *startTime;
@property (nonatomic ,copy)  NSString *endTime;
@property (nonatomic ,strong) NSMutableDictionary *resultDic;
@property (nonatomic ,strong) NSMutableArray *tempIndicators;
@property (nonatomic ,strong) NSMutableArray *btns;
@property (nonatomic ,assign) BOOL isShowTableView;
@property (nonatomic ,assign) BOOL isShowDatePickerView;
//@property (nonatomic ,strong) CHDatePickerView *pickerView;


@end
@implementation CHSuperMenu

-(NSMutableArray *)btns{
    if (!_btns) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

-(NSMutableDictionary *)resultDic{
    if (!_resultDic) {
        _resultDic = [NSMutableDictionary dictionary];
    }
    return _resultDic;
}

//-(NSMutableArray *)dateArr{
//    if (!_dateArr) {
//        _dateArr = [NSMutableArray array];
//    }
//    return _dateArr;
//}
-(NSMutableArray *)tempIndicators{
    if (!_tempIndicators) {
        _tempIndicators = [NSMutableArray array];
    }
    return _tempIndicators;
}

-(UIButton *)coverBtn{
    
    if (!_coverBtn) {
        _coverBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.x, self.y, UIScreenW, UIScreenH)];
        [_coverBtn addTarget:self action:@selector(coverBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coverBtn;
    
}


-(instancetype)initWithFrame:(CGRect)frame withTitles:(NSArray *)titles{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        _titles = titles;
        _MArray = [NSMutableArray new];
        _isShowTableView = NO;
        _isShowDatePickerView = NO;
        
        //        获取当前月份的所有日期
        [self initData];
        
        [self buildUI];
    }
    return self;
}

//-(void)getAllDaysInCurrentMonth{
//
//
//    //    获取当月的总天数
//
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//
//    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
//
//    NSUInteger numberOfDaysInMonth = range.length;
//
//    //2.获取当前年份, 月份, 号数
//
//    unsigned unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay;
//
//    NSDateComponents *components = [calendar components:unitFlags fromDate:[NSDate date]];
//
//    for (NSInteger i = 1; i < numberOfDaysInMonth+1; i++) {
//
//        NSString *date = [NSString stringWithFormat:@"%ld-%.2ld-%.2zd",(long)components.year,components.month,i];
//
//        [self.dateArr addObject:date];
//
//    }
//
//
//}


-(void)buildUI{
    
    
    CGFloat btnW  = UIScreenW / _titles.count;
    for (int i = 0; i< _titles.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        btn.titleLabel.font = Font(14);
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [btn setTitle:_titles[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"333333" alpha:1.0f] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(i*btnW, 0, btnW, self.h);
        [self addSubview:btn];
        [self.btns addObject:btn];
        
        //indicatorLayer
        CGPoint indicatorPosition = CGPointMake((i + 1) * (UIScreenW /_titles.count) -20, self.h / 2);
        CAShapeLayer *sharpLayer = [self createIndicatorWithPosition:indicatorPosition color:[UIColor grayColor]];
        [self.layer addSublayer:sharpLayer];
        [self.tempIndicators addObject:sharpLayer];
        
    }
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, self.h -0.5, self.w, 0.5)];
    line.backgroundColor = [UIColor colorWithHexString:@"098edd" alpha:1.0f];
    [self addSubview:line];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.x, self.y+self.h, UIScreenW, 0) style:UITableViewStylePlain];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 40;
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        // 如果tableView响应了setSeparatorInset: 这个方法,我们就将tableView分割线的内边距设为0.
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        // 如果tableView响应了setLayoutMargins: 这个方法,我们就将tableView分割线的间距距设为0.
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
    UIView *datePickerView = [[UIView alloc] initWithFrame:CGRectMake(0, UIScreenH, UIScreenW, 270)];
    datePickerView.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];
    [self addSubview:datePickerView];
    self.datePickerView = datePickerView;
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 40, 40)];
    cancelBtn.titleLabel.font = Font(16);
    [cancelBtn setTitleColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f] forState:UIControlStateNormal];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [datePickerView addSubview:cancelBtn];
    
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 50, 0, 40, 40)];
    sureBtn.titleLabel.font = Font(16);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [datePickerView addSubview:sureBtn];
    
    self.startTime = _MArray[0];
    self.endTime = _MArray[0];
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, UIScreenW, 230)];
    pickerView.backgroundColor = [UIColor whiteColor];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    self.pickerView = pickerView;
    [datePickerView addSubview:pickerView];
    
}

//指示器
- (CAShapeLayer *)createIndicatorWithPosition:(CGPoint)position color:(UIColor *)color {
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(8, 0)];
    [path addLineToPoint:CGPointMake(4, 5)];
    [path closePath];
    
    layer.path = path.CGPath;
    layer.lineWidth = 0.8;
    layer.fillColor = color.CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    CGPathRelease(bound);
    layer.position = position;
    
    return layer;
}

#pragma mark - 动画
- (void)animateIndicator:(CAShapeLayer *)indicator reverse:(BOOL)reverse{
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.25];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4 :0.0 :0.2 :1.0]];
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    anim.values = reverse ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];
    
    if (!anim.removedOnCompletion) {
        [indicator addAnimation:anim forKey:anim.keyPath];
    } else {
        [indicator addAnimation:anim forKey:anim.keyPath];
        [indicator setValue:anim.values.lastObject forKeyPath:anim.keyPath];
    }
    
    [CATransaction commit];
        if (reverse) {
            indicator.fillColor =  [UIColor colorWithHexString:@"098edd" alpha:1.0f].CGColor;
        }else {
            indicator.fillColor = [UIColor grayColor].CGColor;
        }
//        complete();
}

-(void)sureBtnClick:(UIButton *)btn{
    
    int restut = [self compareOneDay:self.startTime withAnotherDay:self.endTime];
    if (restut == 1) {
        [MBProgressHUD showError:@"开始日期不得大于结束日期"];
    }else{
        [self.selectedBtn setTitle:self.startTime forState:UIControlStateNormal];
        
        self.resultDic[@"starttime"] = self.startTime;
        self.resultDic[@"endtime"] = self.endTime;
        
        if ([self.delegate respondsToSelector:@selector(superMenu:didSelectRowInCoulumn:backToResultDict:)]) {
            [self.delegate superMenu:self didSelectRowInCoulumn:_currentSelectedColumn backToResultDict:self.resultDic];
        }
    }
    [self coverBtnClick];
}


-(void)cancelBtnClick:(UIButton *)btn{
    
    [self coverBtnClick];
}


//   遮罩层点击
-(void)coverBtnClick{
    
    [UIView animateWithDuration:0.2 animations:^{
        for (CAShapeLayer *sharpLayer in self.tempIndicators) {
            [self animateIndicator:sharpLayer reverse:NO];
        }
        
        for (UIButton *btn  in self.btns) {
            if (btn.selected == YES) {
                btn.selected = NO;
            }
        }
        self.tableView.frame = CGRectMake(self.x, self.y+self.h, UIScreenW, 0);
        self.datePickerView.frame = CGRectMake(0, UIScreenH, UIScreenW, 270);
        self.coverBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        [self.coverBtn removeFromSuperview];
        _isShowTableView  = NO;
        _isShowDatePickerView = NO;
        
    }];
    
 
    
}

-(void)btnClick:(UIButton *)btn{
    NSLog(@"%zd----%zd",btn.tag,self.selectedBtn.tag);
    _currentSelectedColumn = btn.tag;
    
    if (btn!= self.selectedBtn ) {
        self.selectedBtn.selected = NO;
        btn.selected = YES;

        if (btn.tag == self.selectedBtn.tag) {
           [self animateIndicator:self.tempIndicators[btn.tag] reverse:YES];
        }else{
            [self animateIndicator:self.tempIndicators[btn.tag] reverse:YES];
            [self animateIndicator:self.tempIndicators[self.selectedBtn.tag] reverse:NO];
        }
        self.selectedBtn = btn;
        
    }else{
        
        self.selectedBtn.selected = !self.selectedBtn.selected;
        if (self.selectedBtn.selected == YES) {
            [self animateIndicator:self.tempIndicators[btn.tag] reverse:YES];
        }else{
            [self animateIndicator:self.tempIndicators[btn.tag] reverse:NO];
        }
    }
    if (btn.tag == 2) {
        
        if (_isShowTableView) {
            self.tableView.frame = CGRectMake(self.x, self.y+self.h, UIScreenW, 0);
        }
        if (_isShowDatePickerView == YES) {
            [self coverBtnClick];
            _isShowDatePickerView = NO;
            
        }else{
            
            [UIView animateWithDuration:0.2 animations:^{
                
                self.coverBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
                [self.superview addSubview:self.coverBtn];
                [self.coverBtn.superview addSubview:self];
                
                self.datePickerView.frame = CGRectMake(0, UIScreenH - 270 -64, UIScreenW, 270);
                [self.superview addSubview:self.datePickerView];
                _isShowDatePickerView = YES;
            }];
            
            
        }
    }else{
        
        if (_isShowDatePickerView) {
            
            self.datePickerView.frame = CGRectMake(0, UIScreenH, UIScreenW, 270);
            _isShowDatePickerView = NO;
        }
        
        if (!_isShowTableView ) {
            
            NSArray *titles = [_dataSource menu:self titleForRowInCoulumn:_currentSelectedColumn];
            CGFloat tableViewH = titles.count *40;
            if (tableViewH > UIScreenH - 64-44 ) {
                tableViewH = UIScreenH - 64-44;
            }
            
            [UIView animateWithDuration:0.3 animations:^{
                
                self.coverBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
                [self.superview addSubview:self.coverBtn];
                [self.coverBtn.superview addSubview:self];
                self.tableView.frame = CGRectMake(self.x, self.y+self.h, UIScreenW, tableViewH);
                [self.superview addSubview:self.tableView];
                _isShowTableView = YES;
            }];
        
        }else{
            
            if (btn.selected == YES ) {
                [self coverBtnClick];
                
                NSArray *titles = [_dataSource menu:self titleForRowInCoulumn:_currentSelectedColumn];
                CGFloat tableViewH = titles.count *40;
                if (tableViewH > UIScreenH - 64-44 ) {
                    tableViewH = UIScreenH - 64-44;
                }
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.coverBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
                    [self.superview addSubview:self.coverBtn];
                    [self.coverBtn.superview addSubview:self];
                    self.tableView.frame = CGRectMake(self.x, self.y+self.h, UIScreenW, tableViewH);
                    [self.superview addSubview:self.tableView];
                }];
                
            }else{
                
                _isShowTableView = NO;
                [self coverBtnClick];
            }
            
        }
        
        
        [self.tableView reloadData];
    }
}



#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dataSource menu:self numberOfRowsInColumn:_currentSelectedColumn];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    };
    
    cell.textLabel.font = Font(14);
    NSArray *titles = [_dataSource menu:self titleForRowInCoulumn:_currentSelectedColumn];
    cell.textLabel.text = titles[indexPath.row];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSArray *titles = [_dataSource menu:self titleForRowInCoulumn:_currentSelectedColumn];
    [self.selectedBtn setTitle:titles[indexPath.row] forState:UIControlStateNormal];
    [self coverBtnClick];
    
    if (_currentSelectedColumn == 0) {
        if (indexPath.row == 0) {
            self.resultDic[@"areaid"] = [Util getValue:@"areaid"];
        }else{
            PJ_Model *model = [Globle getInstance].datas[indexPath.row-1];
            self.resultDic[@"areaid"] = model.areaid;
        }
    }else if(_currentSelectedColumn == 1){
        NSString *title = titles[indexPath.row];
        if ([title isEqualToString:@"未回复"]) {
            self.resultDic[@"state"] = @"0";
        }else if ([title isEqualToString:@"已回复"]){
            self.resultDic[@"state"] = @"1";
        }else{
            self.resultDic[@"state"] = @"";
        }
    }
    
    if ([self.delegate respondsToSelector:@selector(superMenu:didSelectRowInCoulumn:backToResultDict:)]) {
        [self.delegate superMenu:self didSelectRowInCoulumn:_currentSelectedColumn backToResultDict:self.resultDic];
    }
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
}


#pragma mark - UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
//    NSInteger result = 0;
//    switch (component) {
//        case 0:
//            result = self.dateArr.count;//根据数组的元素个数返回几行数据
//            break;
//        case 1:
//            result = self.dateArr.count;
//            break;
//
//        default:
//            break;
//    }
//
//    return result;
    return   _dayRange+_dayRange1;
}


//指定每行如何展示数据（此处和tableview类似）
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString * title = nil;
    switch (component) {
        case 0:
            title = _MArray[row];
            break;
        case 1:
            title = _MArray[row];
            break;
        default:
            break;
    }
    
    return title;
}


//重写方法

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    
    if (!pickerLabel){
        
        pickerLabel = [[UILabel alloc] init];
        
        // Setup label properties - frame, font, colors etc
        
        //adjustsFontSizeToFitWidth property to YES
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setTextColor:[UIColor colorWithHexString:@"666666" alpha:1.0f]];
        
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:14]];
        
    }
    
    
    // Fill the label text here
    
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
    
}

//选中某一行
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"第%zd列 ，第%zd行",component,row);
    
    //记录下滚动结束时的行数
    _selectRow = row;
    _selectComponent = component;
    
    if (component == 0) {
        self.startTime = _MArray[row];
    }else if(component == 1){
        self.endTime = _MArray[row];
    }
    
    
    
    
    [pickerView reloadAllComponents];
    
}

/****
 比较日期大小默认会比较到秒
 ****/
-(int)compareOneDay:(NSString *)oneDayStr withAnotherDay:(NSString *)anotherDayStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        NSLog(@"开始日期不的大于结束日期");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

-(void)initData{
    
    //
    NSDate *date = [NSDate date];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    
    NSArray *array = [dateStr componentsSeparatedByString:@"-"];
    
    _year = [array[0] integerValue] - 1;
    _month = 01;
    _day = 01;
    
    _dayRange = [self isAllDay:_year andMonth:_month];
    _dayRange1 = 365 - [self isAllDay:_year +1 andMonth:[array[1] integerValue]] + [array[2] integerValue];
    
    
    for (int i=0; i<_dayRange+_dayRange1; i++) {
        
        //取出当月的天数
        NSInteger day = [self isAllDay:_year andMonth:_month] - [self isAllDay:_year andMonth:_month+1];
        if (_day > day) {
            _day = 1;
            _month++;
        }
        if (_month>12) {
            _year++;
        }
        _month = _month%13;
        if (_month==0) {
            _month=1;
            
        }
        NSString * string;
        if (i == 0) {
            string = [NSString stringWithFormat:@"%02ld-%02ld-%02ld",_year,_month,_day++];
            _dateStr = string;
        }else{
            
            string = [NSString stringWithFormat:@"%02ld-%02ld-%02ld",_year,_month,_day++];
            
        }
        [_MArray addObject:string];
    }
    
}

#pragma mark - 返回天数
-(NSInteger)isAllDay:(NSInteger)year andMonth:(NSInteger)month{
    int day=0;
    switch(month){
        case 1:
            day += 31;
        case 2:{
            if(((year%4==0)&&(year%100!=0))||(year%400==0)){
                day+=29;
            }
            else{
                day+=28;
            }
        }
        case 3:
            day += 31;
        case 4:
            day += 30;
        case 5:
            day += 31;
        case 6:
            day += 30;
        case 7:
            day += 31;
        case 8:
            day += 31;
        case 9:
            day += 30;
        case 10:
            day += 31;
        case 11:
            day += 30;
        case 12:
            day += 31;
            break;
        default:
            break;
    }
    return day;
}


@end
